package com.liwei.weixin.controller;

import com.liwei.weixin.kit.SecurityKit;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by Liwei on 2015/11/7.
 */
@Controller
public class WeixinController {

    private static Logger logger = Logger.getLogger(WeixinController.class);
    public static final String TOKEN = "liwei";

    /**
     * 验证微信服务器与我们自己的应用交互的 get 方法
     * 对应开发文档：第二步：验证服务器地址的有效性
     */
    @RequestMapping("/wget")
    public void init(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("hello" );
        String signature =  request.getParameter("signature");
        String timestamp =  request.getParameter("timestamp");
        String nonce =  request.getParameter("nonce");
        String echostr =  request.getParameter("echostr");
        logger.debug("signature " + signature);
        logger.debug("timestamp " + timestamp);
        logger.debug("nonce " + nonce);
        logger.debug("echostr " + echostr);
        String[] arrs = {TOKEN,timestamp,nonce};
        logger.debug("排序之前："  + Arrays.asList(arrs));
        Arrays.sort(arrs);
        logger.debug("排序之后："  + Arrays.asList(arrs));

        StringBuffer sb = new StringBuffer();
        for(String a:arrs){
            sb.append(a);
        }

        String sha1 =  SecurityKit.sha1(sb.toString());

        logger.debug("sha1 计算的加密字符串：" + sha1);
        if(sha1.equals(signature)){
            response.getWriter().println(echostr);
        }
    }

    @RequestMapping(value = "/testExceptionHandler")
    public void testExceptionHandler(){
        int i = 1 /0;
    }
}
